package me.phelps.library;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;

import androidx.viewpager.widget.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.File;
import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;

/**
 * Created by phelps on 2015/3/9.
 */
public class PopZoomGallery extends PopupWindow implements View.OnClickListener {

    private Context mContext;
    private ZoomGallery mGallery;
    RelativeLayout rll_bottom;
    LinearLayout lnl_cancel, lnl_save;
    TextView txt_count;
    private View contentView;
    private ArrayList<ZoomImageModel> mZoomImageList;
    private boolean hasBottom;
    private String saveDir;
    int selectedPage;
    private ZoomGalleryAdapter.ZoomGalleryInstantiateItem mItemListener;
    ViewPager.OnPageChangeListener onPageChangeListener;

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener) {
        this.onPageChangeListener = onPageChangeListener;
    }

    public void setSaveDir(String saveDir) {
        this.saveDir = saveDir;
    }

    public void setHasBottom(boolean hasBottom) {
        this.hasBottom = hasBottom;
        if (rll_bottom != null) {
            if (hasBottom) {
                rll_bottom.setVisibility(View.VISIBLE);
            } else {
                rll_bottom.setVisibility(View.GONE);
            }
        }
    }

    @Deprecated
    public PopZoomGallery(Context context, ArrayList<ZoomImageModel> zoomImageList,
                          ZoomGalleryAdapter.ZoomGalleryInstantiateItem itemListener) {
        super(context);
        mContext = context;
        mZoomImageList = zoomImageList;
        mItemListener = itemListener;
        init();
    }

    public PopZoomGallery(final Activity context, final ArrayList<ZoomImageModel> zoomImageList) {
        super(context);
        mContext = context;
        mZoomImageList = zoomImageList;
        mItemListener = new ZoomGalleryAdapter.ZoomGalleryInstantiateItem() {
            @Override
            public void onItemInstantiate(ViewGroup container, int position,
                                          PhotoView view, ImageView img_loading, ZoomImageModel model) {
                Glide.with(context)
                        .load(model.bigImagePath)
//						.centerCrop( )
                        .into(view);
            }
        };
        init();
    }

    private void init() {
        initView();
        setupPop();
    }

    private void initView() {
        contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_zoom_gallery, null);
        rll_bottom = (RelativeLayout) contentView.findViewById(R.id.rll_bottom);
        rll_bottom.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        if (hasBottom) {
            rll_bottom.setVisibility(View.VISIBLE);
        } else {
            rll_bottom.setVisibility(View.GONE);
        }
//		lnl_cancel = (LinearLayout) contentView.findViewById(R.id.lnl_cancle);
        lnl_save = (LinearLayout) contentView.findViewById(R.id.lnl_save);
//		lnl_cancel.setOnClickListener(this);
        lnl_save.setOnClickListener(this);
        txt_count = (TextView) contentView.findViewById(R.id.txt_count);
        mGallery = new ZoomGallery(mContext, this, mItemListener);
        txt_count.setText("1/" + mZoomImageList.size());
        mGallery.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectedPage = position;
                txt_count.setText(position + 1 + "/" + mZoomImageList.size());
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        LinearLayout linearLayout = (LinearLayout) contentView.findViewById(R.id.gallery_container);
        linearLayout.addView(mGallery);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.lnl_cancle) {
            if (mGallery != null) {
                mGallery.close();
            }
        } else if (v.getId() == R.id.lnl_save) {
            if (saveDir == null) {
                Toast.makeText(mContext, "存储路径出错", Toast.LENGTH_SHORT).show();
                return;
            }
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            final File file = new File(dir, System.currentTimeMillis() + ".png");
            Glide.with(mContext).load(mZoomImageList.get(selectedPage).bigImagePath)
                    .downloadOnly(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource,
                                                    GlideAnimation<? super File> glideAnimation) {
                            try {
                                FileOpreateUtils.copyfile(resource, file, true);
                            } catch (FileOpreateUtils.CopyFailedException e) {
                                e.printStackTrace();
                                Toast.makeText(mContext, "图片获取失败", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Toast.makeText(mContext, "图片下载完成，已存入" + saveDir,
                                    Toast.LENGTH_SHORT).show();
                        }

                    });

        }

    }

    private void setupPop() {
        setContentView(contentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable());// 给popupWindow设置背景
        setAnimationStyle(0);
    }

    //显示
    public void showPop(View view, int position) {
        showAtLocation(view, Gravity.CENTER, 0, 0);

        mGallery.open(mZoomImageList, position);

    }


}
